package com.huluspace.learnhub.controller;

import com.huluspace.learnhub.dto.*;
import com.huluspace.learnhub.model.Content;
import com.huluspace.learnhub.security.JwtUtil;
import com.huluspace.learnhub.service.ContentService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/content")
public class ContentController {
  private final ContentService contentService;
  private final JwtUtil jwtUtil;
  public ContentController(ContentService contentService, JwtUtil jwtUtil) {
    this.contentService = contentService;
    this.jwtUtil = jwtUtil;
  }

  @GetMapping("/list")
  public ApiResponse<PageResult<ContentForListDTO>> listContents(
      @RequestParam(name = "page", defaultValue = "1") int page,
      @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
      @RequestParam(name = "type", required = false) String type,
      @RequestParam(name = "keyword", required = false) String keyword
  ) {
    PageResult<ContentForListDTO> result = contentService.getContents(page, pageSize, type, keyword);
    return ApiResponse.success(result);
  }

  @PostMapping("/raw")
  public ApiResponse<String> publishRaw(@RequestBody RawContentDTO dto, HttpServletRequest httpRequest) {
    String username = jwtUtil.extractUserName(jwtUtil.extractToken(httpRequest));
    contentService.publishRaw(dto.getText(), username);
    return ApiResponse.success("内容发布成功");
  }

  // 详情
  @GetMapping("/{id}")
  public ApiResponse<ContentDTO> getContentById(@PathVariable("id") Long id) {
    return contentService.getContentById(id)
            .map(value -> ApiResponse.success(ContentDTO.fromEntity(value)))
            .orElseGet(() -> ApiResponse.error("内容不存在"));
  }

}
